/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

package com.wider.foundation;

import java.util.LinkedHashMap;
import java.util.Map;

/**
 * This class extends the Hash Map to supports LRU-based (Least Recently Used) circular (ring) buffering
 * in a straight forward manner as operating on a conventional Map structure.
 *
 * @author William Choi <avextk@gmail.com>
 */
public class LRURingMap<K,V> extends LinkedHashMap<K,V>{
    public static final int DEFAULT_MAX_CAPACITY = 16;

    private int limit;

    private V superPut(K key, V value){
        return super.put(key, value);
    }

    protected V removeEldestEntry(){
        V removed = null;

        System.out.print("Removing...");
        for (Map.Entry entry: this.entrySet()){
            removed = this.remove(entry.getKey());
            System.out.println("remove: " + entry.getKey() + " : " + entry.getValue());
            break;
        }
        return removed;
    }
    
    public LRURingMap(){
        super(DEFAULT_MAX_CAPACITY, (float) 0.75, true);
        limit = DEFAULT_MAX_CAPACITY;
    }

    public LRURingMap(int max_capacity){
        super(max_capacity, (float) 0.75, true);
        limit = max_capacity;
    }

    public boolean isFull(){
        return (this.size() >= limit);
    }

    @Override
    public V put (K key, V value){
        if (isFull()){
            removeEldestEntry();
        }
        V ret = superPut(key, value);
        return ret;
    }


}
